package org.aplombh.java.leetcode.all;

public class _25K个一组翻转链表 {
}

class Solution25_1 {

    public ListNode reverseKGroup(ListNode head, int k) {

        ListNode pre = new ListNode();
        pre.next = head;

        int len = len(head);
        reverseKGroupByLen(pre, k, len);

        return pre.next;
    }

    public void reverseKGroupByLen(ListNode head, int k, int len) {
        if (len < k)
            return;

        ListNode cur = head.next;
        ListNode pre = cur;

        ListNode save = head.next;
        for (int i = 0; i < k; i++) {
            pre = pre.next;
            cur.next = head.next;
            head.next = cur;
            cur = pre;
        }
        save.next = cur;

        reverseKGroupByLen(save, k, len - k);
    }

    private int len(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }
}